import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:get/get.dart';
import 'package:lighting_driver/src/bluetooth/blemanager_extension.dart';
import 'package:lighting_driver/src/moduls/search/search_view.dart';
import 'package:lighting_driver/src/routes/app_bindings.dart';
import 'package:lighting_driver/src/routes/app_pages.dart';

import 'generated/my_localizations.dart';
import 'src/bluetooth/send_data.dart';
import 'src/const/const.dart';
import 'src/moduls/home/controllers/home_controller.dart';

// 创建 navigatorKey
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await requestPermission();
  BluetoothManager.key = navigatorKey;
  BluetoothManager.autoConnectDuringScan = true;
  BluetoothManager.isScanloop = true;
  BluetoothManager.instance.startScan(deviceNameFilter: filterName, duration: const Duration(seconds: 2));
  await Future.delayed(const Duration(milliseconds: 800)); // 等待一段时间确保停止

  AppBindings.initGetx();
  runApp(const MyApp());
}

void initRealm() {
  // // 创建不同模型的 RealmManager 实例
  RealmManager.schemaVersion = 2;
  // 创建不同模型的 RealmManager 实例
}

Future<void> requestPermission() async {
  BluetoothManager.instance.requestPermissions();
  BluetoothManager.maxConnectedEnable = 4;
}

MyLocalizations? loc;

class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  final HomeController controller = Get.find<HomeController>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  Locale _getSupportedLocale(String code) {
    switch (code) {
      case 'zh':
        return const Locale('zh');
      case 'en':
        return const Locale('en');
      default:
        return const Locale('en'); // 默认英文
    }
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    listenBluetooth(context);
    return GetMaterialApp(
      navigatorKey: navigatorKey,

      title: 'Lighting Driver',

      /// 💡 跟随系统语言
      locale: null,

      /// 💡 设置多语言
      supportedLocales: MyLocalizations.supportedLocales,
      localizationsDelegates: MyLocalizations.localizationsDelegates,

      /// 💡 根据系统语言变化更新 controller.loc
      localeResolutionCallback: (locale, supportedLocales) {
        final langCode = locale?.languageCode ?? 'en';
        final supportedLocale = _getSupportedLocale(langCode);
        final loc = lookupMyLocalizations(supportedLocale); // 自定义一个 lookup 函数
        controller.loc = loc;
        controller.refreshLocale();
        return supportedLocale;
      },

      theme: ThemeData(
        splashColor: bgColor.withOpacity(0.5),
        // brightness: Brightness.dark, // 启用暗色主题
        scaffoldBackgroundColor: bgColor, // 页面背景黑色
        appBarTheme: const AppBarTheme(
          backgroundColor: bgColor, // AppBar 背景黑色
          foregroundColor: Colors.white, // AppBar 图标、文字白色
        ),
        iconTheme: const IconThemeData(color: Colors.white), // 图标颜色
        textTheme: const TextTheme(
          bodyMedium: TextStyle(color: Colors.white), // 正文文字白色
        ),
      ),
      initialRoute: AppPages.INITIAL,
      initialBinding: AppBindings(),
      getPages: AppPages.routes,
      debugShowCheckedModeBanner: false,
      builder: EasyLoading.init(),
    );
  }
}

extension _MyAppStateExtension on _MyAppState {
  void listenBluetooth(BuildContext context) {
    ///监听蓝牙外设连接状态
    BluetoothManager.instance.connectionStateStream.listen((value) {
      var state = value.values.first;
      switch (state) {
        case BluetoothConnectionState.connected:
          EasyLoading.showSuccess('Connect successfully');
          BluetoothManager.instance.isConnectedRx = true;
          listen();
        case BluetoothConnectionState.disconnected:
          BluetoothManager.instance.isConnectedRx = false;
          EasyLoading.showSuccess('disConnected!', duration: const Duration(milliseconds: 1500));
        case BluetoothConnectionState.connecting:
          break;
        case BluetoothConnectionState.disconnecting:
          print('设备断开连接中');
          break;
      }
    });

    ///监听蓝牙广播状态
    BluetoothManager.instance.bluetoothStateStream.listen((state) {
      switch (state) {
        case BluetoothAdapterState.on:
          break;
        case BluetoothAdapterState.off:
          BluetoothManager.instance.isConnectedRx = false;
        //EasyLoading.showInfo('Bluetooth turned off');
        default:
      }
    }, onError: (error) {
      EasyLoading.showInfo('${error.message}');
    });
  }

  void listen() {
    ///监听数据回调
    BluetoothManager.instance.read(
        service_uuid: read_service,
        characteristics_uuid: read_uuid,
        onResponse: (data) {
          print('收到蓝牙上传的数据是 == ${data.toHexstr(' |')}');
        });
  }
}
